//
//  MJPhotoBrowser.m
//
//  Created by mj on 13-3-4.
//  Copyright (c) 2013年 itcast. All rights reserved.

#import <QuartzCore/QuartzCore.h>
#import "LocalMJPhotoBrowser.h"
#import "MJPhoto.h"
#import "MJPhotoView.h"
#import "MJPhotoToolbar.h"
#import "Config.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <ShareSDK/ShareSDK.h>
//#import "MyCloudPhotoToolBar.h"
//#import "ElseCloudPhotoToolBar.h"

#define kPadding 10
#define kPhotoViewTagOffset 1000
#define kPhotoViewIndex(photoView) ([photoView tag] - kPhotoViewTagOffset)

@interface LocalMJPhotoBrowser () <MJPhotoViewDelegate>
{
    // 滚动的view
    UIScrollView *_photoScrollView;
    // 所有的图片view
    NSMutableSet *_visiblePhotoViews;
    NSMutableSet *_reusablePhotoViews;
    // 工具条
    MJPhotoToolbar *_toolbar;
    
    // 一开始的状态栏
    BOOL _statusBarHiddenInited;
    
    UIView *navbarView;
    
    UILabel *photoIndexLabel;
}
@end

@implementation LocalMJPhotoBrowser

#pragma mark - Lifecycle
- (void)loadView
{
    _statusBarHiddenInited = [UIApplication sharedApplication].isStatusBarHidden;
    // 隐藏状态栏
    //    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
    self.view = [[UIView alloc] init];
    self.view.frame = [UIScreen mainScreen].bounds;
    self.view.backgroundColor = [UIColor blackColor];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor blackColor];
    
    // 创建UIScrollView
    [self createScrollView];
    
    // 创建导航条
    [self createNavbar];
    
    // 创建工具条
//    [self createToolbar];
}



- (void)show
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self.view];
    [window.rootViewController addChildViewController:self];
    
    if (_currentPhotoIndex == 0) {
        [self showPhotos];
    }
}

#pragma mark 创建工具条

-(void)createNavbar{
    if (!navbarView) {
        navbarView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44+(OSVersionIsAtLeastiOS7?20:0))];
        [self.view addSubview:navbarView];
        navbarView.backgroundColor = RGBA(0, 0, 0, 0.16);
        
        UIButton *backBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        [backBtn setFrame:CGRectMake(9, navbarView.bounds.size.height - 42, 40, 40)];
        [backBtn  addTarget:self action:@selector(navLeftAction) forControlEvents:UIControlEventTouchUpInside];
        [backBtn setImage:[UIImage imageNamed:@"common_backbtn"] forState:UIControlStateNormal];
        [backBtn setImage:[UIImage imageNamed:@"common_backbtn_h"] forState:UIControlStateHighlighted];
        
        [navbarView addSubview:backBtn];
        
        photoIndexLabel=[[UILabel alloc]initWithFrame:CGRectMake(0,navbarView.bounds.size.height - 44 , navbarView.bounds.size.width, 44)];
        [navbarView addSubview:photoIndexLabel];
        photoIndexLabel.textAlignment=NSTextAlignmentCenter;
        photoIndexLabel.textColor=[UIColor whiteColor];
        photoIndexLabel.backgroundColor = [UIColor clearColor];
    }
}

-(void)navLeftAction{
    
    NSInteger tag = kPhotoViewTagOffset + self.currentPhotoIndex;
    
    MJPhotoView *photoView =  (MJPhotoView *)[_photoScrollView viewWithTag:tag];
    [photoView dismissAction];
    
}

//- (void)createToolbar
//{
//    CGFloat barHeight = 60;
//    CGFloat barY = self.view.frame.size.height - barHeight;
//    
//    UIView *barView = [[UIView alloc] initWithFrame: CGRectMake(0, barY, self.view.frame.size.width, barHeight)];
//    barView.backgroundColor=RGBA(0,0, 0, 0.16);
//    [self.view addSubview:barView];
//    
//    CGFloat BtnWidth = 100;
//    NSArray *itmes = @[@"分享"];
//    CGFloat interVal = (self.view.frame.size.width - BtnWidth *itmes.count)/(itmes.count+1);
//    for(int i = 0;i<itmes.count;i++){
//        UIButton*btn = [UIButton buttonWithType:UIButtonTypeCustom];
//        btn.frame = CGRectMake(interVal*(i+1)+BtnWidth*i, (barView.frame.size.height -34)/2, BtnWidth, 34);
//        [btn.titleLabel setFont:MAIN_FONF_14];
//        [btn.titleLabel setTextColor:[UIColor whiteColor]];
//        [btn setBackgroundImage:[UIImage imageNamed:@"phototool_btnbk"] forState:UIControlStateNormal];
//        
//        [btn setTitle:itmes[i] forState:UIControlStateNormal];
//        [btn addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
//        [barView addSubview:btn];
//        btn.tag=100+i;
//        btn.titleLabel.textAlignment = NSTextAlignmentCenter;
//    }
//    
//    [self updatePageState];
//    
//}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}
//
//-(void)action:(UIButton*)sender{
//    NSInteger tag = sender.tag;
//    
//    switch (tag) {
//        case 100:
//            [self shareLocalPhoto];
//            break;
//            
//        default:
//            break;
//    }
//    
//}
//
//#pragma mark - MJPhotoToolbarDelegate
////分享当前显示的图片
//- (void)shareLocalPhoto{
//    
//    MJPhoto *photo = _photos[_currentPhotoIndex];
//    
//    id<ISSCAttachment>image = [ShareSDK jpegImageWithImage:photo.image quality:1];
//    
//    //    NSString *url = [NSString stringWithFormat:@"%@",photo.photoUrl];
//    //构造分享内容
//    
//    id<ISSContent> publishContent = [ShareSDK content:@"我在#爱维宝贝#分享了一张照片给大家"
//                                     
//                                       defaultContent:@"我在#爱维宝贝#分享了一张照片给大家"
//                                                image:image
//                                                title:@"我在#爱维宝贝#分享了一张照片给大家"
//                                                  url:@""
//                                          description:NSLocalizedString(@"爱维宝贝照片分享", @"我在#爱维宝贝#分享了一张照片给大家")
//                                     
//                                            mediaType:SSPublishContentMediaTypeImage];
//    
//    
//    
//    //定制QQ空间信息
//    
//    [publishContent addQQSpaceUnitWithTitle:INHERIT_VALUE                                        url:@"http://www.aiwei365.com/"
//                                       site:nil
//                                    fromUrl:nil
//                                    comment:INHERIT_VALUE
//                                    summary:INHERIT_VALUE
//                                      image:INHERIT_VALUE
//                                       type:INHERIT_VALUE
//                                    playUrl:nil
//                                       nswb:nil];
//    
//    //定制微信好友信息
//    
//    [publishContent addWeixinSessionUnitWithType:INHERIT_VALUE
//     
//                                         content:INHERIT_VALUE
//                                           title:NSLocalizedString(@"我在#爱维宝贝#分享了一张照片", @"我在#爱维宝贝#分享了一张照片")
//                                             url:INHERIT_VALUE
//                                      thumbImage:image
//                                           image:INHERIT_VALUE
//                                    musicFileUrl:nil
//                                         extInfo:nil
//                                        fileData:nil
//                                    emoticonData:nil];
//    
//    [publishContent addWeixinTimelineUnitWithType:INHERIT_VALUE content:INHERIT_VALUE title:INHERIT_VALUE url:INHERIT_VALUE image:INHERIT_VALUE musicFileUrl:nil extInfo:nil fileData:nil emoticonData:nil];
//    
//    //弹出分享菜单
//    
//    [ShareSDK showShareActionSheet:nil
//     
//                         shareList:nil
//                           content:publishContent
//                     statusBarTips:YES
//                       authOptions:nil
//                      shareOptions:nil
//                            result:^(ShareType type, SSResponseState state, id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
//                            
//                                if (state == SSResponseStateSuccess)
//                                    
//                                {
//                                NSLog(NSLocalizedString(@"TEXT_ShARE_SUC", @"分享成功"));
//                                    
//                                }
//                                
//                                else if (state == SSResponseStateFail)
//                                    
//                                {
//                                    
//                                    NSLog(@"%@", error.errorDescription);
//                                    MBALERT(@"分享失败");
//                                    
//                                }
//                                
//                            }];
//}
//
//


#pragma mark 创建UIScrollView
- (void)createScrollView
{
    CGRect frame = self.view.bounds;
    frame.origin.x -= kPadding;
    frame.size.width += (2 * kPadding);
    _photoScrollView = [[UIScrollView alloc] initWithFrame:frame];
    _photoScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _photoScrollView.pagingEnabled = YES;
    _photoScrollView.delegate = self;
    _photoScrollView.showsHorizontalScrollIndicator = NO;
    _photoScrollView.showsVerticalScrollIndicator = NO;
    _photoScrollView.backgroundColor = [UIColor clearColor];
    _photoScrollView.contentSize = CGSizeMake(frame.size.width * _photos.count, 0);
    [self.view addSubview:_photoScrollView];
    _photoScrollView.contentOffset = CGPointMake(_currentPhotoIndex * frame.size.width, 0);
}

- (void)setPhotos:(NSArray *)photos
{
    _photos = photos;
    
    if (photos.count > 1) {
        _visiblePhotoViews = [NSMutableSet set];
        _reusablePhotoViews = [NSMutableSet set];
    }
    
    for (int i = 0; i<_photos.count; i++) {
        MJPhoto *photo = _photos[i];
        photo.index = i;
        photo.firstShow = i == _currentPhotoIndex;
    }
}

#pragma mark 设置选中的图片
- (void)setCurrentPhotoIndex:(NSUInteger)currentPhotoIndex
{
    _currentPhotoIndex = currentPhotoIndex;
    
    for (int i = 0; i<_photos.count; i++) {
        MJPhoto *photo = _photos[i];
        photo.firstShow = i == currentPhotoIndex;
    }
    
    if ([self isViewLoaded]) {
        _photoScrollView.contentOffset = CGPointMake(_currentPhotoIndex * _photoScrollView.frame.size.width, 0);
        
        // 显示所有的相片
        [self showPhotos];
    }
}

#pragma mark - MJPhotoView代理
- (void)photoViewSingleTap:(MJPhotoView *)photoView
{
    //    [UIApplication sharedApplication].statusBarHidden = _statusBarHiddenInited;
    self.view.backgroundColor = [UIColor clearColor];
    
    // 移除工具条
    [_toolbar removeFromSuperview];
}

- (void)photoViewDidEndZoom:(MJPhotoView *)photoView
{
    [self.view removeFromSuperview];
    [self removeFromParentViewController];
}

- (void)photoViewImageFinishLoad:(MJPhotoView *)photoView
{
    //    _toolbar.currentPhotoIndex = _currentPhotoIndex;
}

#pragma mark 显示照片
- (void)showPhotos
{
    // 只有一张图片
    if (_photos.count == 1) {
        [self showPhotoViewAtIndex:0];
        return;
    }
    
    CGRect visibleBounds = _photoScrollView.bounds;
    NSInteger firstIndex = (int)floorf((CGRectGetMinX(visibleBounds)+kPadding*2) / CGRectGetWidth(visibleBounds));
    NSInteger lastIndex  = (int)floorf((CGRectGetMaxX(visibleBounds)-kPadding*2-1) / CGRectGetWidth(visibleBounds));
    if (firstIndex < 0) firstIndex = 0;
    if (firstIndex >= _photos.count) firstIndex = _photos.count - 1;
    if (lastIndex < 0) lastIndex = 0;
    if (lastIndex >= _photos.count) lastIndex = _photos.count - 1;
    
    // 回收不再显示的ImageView
    NSInteger photoViewIndex;
    for (MJPhotoView *photoView in _visiblePhotoViews) {
        photoViewIndex = kPhotoViewIndex(photoView);
        if (photoViewIndex < firstIndex || photoViewIndex > lastIndex) {
            [_reusablePhotoViews addObject:photoView];
            [photoView removeFromSuperview];
        }
    }
    
    [_visiblePhotoViews minusSet:_reusablePhotoViews];
    while (_reusablePhotoViews.count > 2) {
        [_reusablePhotoViews removeObject:[_reusablePhotoViews anyObject]];
    }
    
    for (NSUInteger index = firstIndex; index <= lastIndex; index++) {
        if (![self isShowingPhotoViewAtIndex:index]) {
            [self showPhotoViewAtIndex:index];
        }
    }
}

#pragma mark 显示一个图片view
- (void)showPhotoViewAtIndex:(NSUInteger)index
{
    NSLog(@"index=%@", @(index));
    
    MJPhotoView *photoView = [self dequeueReusablePhotoView];
    if (!photoView) { // 添加新的图片view
        photoView = [[MJPhotoView alloc] init];
        photoView.photoViewDelegate = self;
    }
    
    // 调整当期页的frame
    CGRect bounds = _photoScrollView.bounds;
    CGRect photoViewFrame = bounds;
    photoViewFrame.size.width -= (2 * kPadding);
    photoViewFrame.origin.x = (bounds.size.width * index) + kPadding;
    photoView.tag = kPhotoViewTagOffset + index;
    
    MJPhoto *photo = _photos[index];
    photoView.frame = photoViewFrame;
    photoView.photo = photo;
    
    [_visiblePhotoViews addObject:photoView];
    [_photoScrollView addSubview:photoView];
    
    [self loadImageNearIndex:index];
}

#pragma mark 加载index附近的图片
- (void)loadImageNearIndex:(NSUInteger)index
{
    if (index > 0) {
        MJPhoto *photo = _photos[index - 1];
        NSURL *url = [NSURL URLWithString:photo.photoUrl];
        
        [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:url options:SDWebImageDownloaderLowPriority progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
        } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
            
        }];
    }
    
    if (index < _photos.count - 1) {
        MJPhoto *photo = _photos[index + 1];
        NSURL *url = [NSURL URLWithString:photo.photoUrl];
        
        [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:url options:SDWebImageDownloaderLowPriority progress:^(NSInteger receivedSize, NSInteger expectedSize) {
            
        } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
            
        }];
    }
}

#pragma mark index这页是否正在显示
- (BOOL)isShowingPhotoViewAtIndex:(NSUInteger)index {
    for (MJPhotoView *photoView in _visiblePhotoViews) {
        if (kPhotoViewIndex(photoView) == index) {
            return YES;
        }
    }
    return  NO;
}

#pragma mark 循环利用某个view
- (MJPhotoView *)dequeueReusablePhotoView
{
    MJPhotoView *photoView = [_reusablePhotoViews anyObject];
    if (photoView) {
        [_reusablePhotoViews removeObject:photoView];
    }
    return photoView;
}

#pragma mark 更新页码状态
- (void)updatePageState
{
    _currentPhotoIndex = _photoScrollView.contentOffset.x / _photoScrollView.frame.size.width;
    
    photoIndexLabel.text = [NSString stringWithFormat:@"%@/%@", @(_currentPhotoIndex+1), @(self.photos.count)];
}

#pragma mark - UIScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self showPhotos];
    [self updatePageState];
}


@end